<template>
  <div class="distribution-container">
    <!-- 规则展示卡片 -->
    <el-card shadow="hover" class="rule-card">
      <div slot="header" class="card-header">
        <h2 class="card-title">
          <i class="el-icon-s-operation"></i> 当前分配规则
        </h2>
        <div class="card-actions">
          <el-button
              type="primary"
              size="small"
              @click="showEditModal = true"
              icon="el-icon-edit"
          >
            修改规则
          </el-button>
          <el-button
              type="success"
              size="small"
              @click="confirmDistribution"
              icon="el-icon-share"
          >
            执行分配
          </el-button>
        </div>
      </div>

      <div class="rule-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="规则名称">
            <el-tag>{{ rule.ruleName || '未设置' }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="预留成本">
            <el-progress
                :percentage="rule.reserve"
                :color="reserveColor"
                :format="formatPercentage"
            />
          </el-descriptions-item>
          <el-descriptions-item label="分红比例">
            <el-progress
                :percentage="rule.dividend"
                color="#67C23A"
                :format="formatPercentage"
            />
          </el-descriptions-item>
          <el-descriptions-item label="管理员分红">
            <el-progress
                :percentage="rule.admin"
                color="#E6A23C"
                :format="formatPercentage"
            />
          </el-descriptions-item>
          <el-descriptions-item label="投资者分红">
            <el-progress
                :percentage="rule.investor"
                color="#409EFF"
                :format="formatPercentage"
            />
          </el-descriptions-item>
          <el-descriptions-item label="农户分红">
            <el-progress
                :percentage="rule.farmer"
                color="#F56C6C"
                :format="formatPercentage"
            />
          </el-descriptions-item>
          <el-descriptions-item label="生效日期">
            <span class="date-text">
              <i class="el-icon-date"></i>
              {{ rule.effectiveDate ? formatDate(rule.effectiveDate) : '未设置' }}
            </span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>

    <!-- 编辑规则弹窗 -->
    <el-dialog
        title="编辑分配规则"
        :visible.sync="showEditModal"
        width="600px"
        :close-on-click-modal="false"
    >
      <div class="dialog-content">
        <!-- 规则名展示 -->
        <div class="form-item">
          <label class="form-label">规则名称：</label>
          <el-tag type="info">{{ rule.ruleName || '未设置' }}</el-tag>
        </div>

        <!-- 成本分配部分 -->
        <el-divider content-position="left"><i class="el-icon-money"></i> 成本分配</el-divider>
        <div class="form-item">
          <label class="form-label">预留成本：</label>
          <el-input-number
              v-model.number="rule.reserve"
              :min="0"
              :max="100"
              :step="1"
              controls-position="right"
              @change="validateReserve"
          >
            <template slot="append">%</template>
          </el-input-number>
          <span class="hint-text">(剩余 {{ 100 - (rule.reserve || 0) }}% 用于分红)</span>
          <div class="error-text" v-if="reserveError">{{ reserveError }}</div>
        </div>

        <!-- 分红分配部分 -->
        <el-divider content-position="left"><i class="el-icon-s-data"></i> 分红分配</el-divider>
        <div class="form-item">
          <label class="form-label">管理员：</label>
          <el-input-number
              v-model.number="rule.admin"
              :min="0"
              :max="100"
              :step="1"
              controls-position="right"
              @change="validateDistribution"
          >
            <template slot="append">%</template>
          </el-input-number>
        </div>

        <div class="form-item">
          <label class="form-label">投资者：</label>
          <el-input-number
              v-model.number="rule.investor"
              :min="0"
              :max="100"
              :step="1"
              controls-position="right"
              @change="validateDistribution"
          >
            <template slot="append">%</template>
          </el-input-number>
        </div>

        <div class="form-item">
          <label class="form-label">农户：</label>
          <el-input-number
              v-model.number="rule.farmer"
              :min="0"
              :max="100"
              :step="1"
              controls-position="right"
              @change="validateDistribution"
          >
            <template slot="append">%</template>
          </el-input-number>
        </div>

        <div class="distribution-summary">
          <el-alert
              :title="`当前分配: ${distributionSum}%`"
              :type="distributionSum === 100 ? 'success' : 'error'"
              :closable="false"
          >
            <span v-if="distributionError">{{ distributionError }}</span>
            <span v-else-if="distributionSum === 100">分配比例正确</span>
          </el-alert>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeModal">取 消</el-button>
        <el-button
            type="primary"
            @click="saveChanges"
            :loading="saving"
            :disabled="!isFormValid"
        >
          保 存
        </el-button>
      </span>
    </el-dialog>

    <!-- 分配确认对话框 -->
    <el-dialog
        title="确认分配"
        :visible.sync="showConfirmDialog"
        width="400px"
    >
      <div class="confirm-content">
        <el-alert
            title="即将按照当前规则执行收益分配"
            type="warning"
            :closable="false"
            show-icon
        >
          <p>请确认分配比例是否正确</p>
        </el-alert>

        <div class="summary-box">
          <div class="summary-item">
            <span class="summary-label">预留成本：</span>
            <span class="summary-value">{{ rule.reserve }}%</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">管理员：</span>
            <span class="summary-value">{{ rule.admin }}%</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">投资者：</span>
            <span class="summary-value">{{ rule.investor }}%</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">农户：</span>
            <span class="summary-value">{{ rule.farmer }}%</span>
          </div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showConfirmDialog = false">再检查</el-button>
        <el-button
            type="primary"
            @click="executeDistribution"
            :loading="distributing"
        >
          确认分配
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getRuleInfoApi, updateRuleInfoApi, executeDistributionApi } from "@/api/distribution";

export default {
  data() {
    return {
      rule: {
        ruleName: '',
        reserve: 0,
        dividend: 0,
        admin: 0,
        investor: 0,
        farmer: 0,
        effectiveDate: ''
      },
      showEditModal: false,
      showConfirmDialog: false,
      saving: false,
      distributing: false,
      reserveError: '',
      distributionError: ''
    };
  },
  computed: {
    reserveColor() {
      const reserve = this.rule.reserve || 0;
      if (reserve < 30) return '#67C23A';
      if (reserve < 60) return '#E6A23C';
      return '#F56C6C';
    },
    distributionSum() {
      return (Number(this.rule.admin) + Number(this.rule.investor) + Number(this.rule.farmer)) || 0;
    },
    isFormValid() {
      return !this.reserveError && !this.distributionError &&
          (Number(this.rule.reserve) + Number(this.rule.dividend) === 100 &&
              this.distributionSum === 100)
    }
  },
  methods: {
    formatPercentage(percentage) {
      return `${percentage}%`;
    },
    formatDate(dateStr) {
      if (!dateStr) return '';
      return dateStr.split('T')[0];
    },
    validateReserve() {
      const reserve = Number(this.rule.reserve)
      if (isNaN(reserve)){
        this.reserveError = '请输入有效数字'
      } else if (reserve < 0 || reserve > 100) {
        this.reserveError = '请输入0-100之间的数字';
      } else {
        this.reserveError = '';
        this.rule.dividend = 100 - reserve;
      }
    },
    validateDistribution() {
      const sum = this.distributionSum;
      if (sum !== 100) {
        this.distributionError = `分红分配总和必须为100%，当前为${sum}%`;
      } else {
        this.distributionError = '';
      }
    },
    closeModal() {
      this.reserveError = '';
      this.distributionError = '';
      this.showEditModal = false;
    },
    async saveChanges() {
      if (!this.isFormValid) return;

      this.saving = true;
      try {
        await updateRuleInfoApi(this.rule);
        this.$message.success('规则更新成功');
        this.closeModal();
        this.getRuleInfo();
      } catch (error) {
        this.$message.error('规则更新失败: ' + (error.message || '未知错误'));
      } finally {
        this.saving = false;
      }
    },
    getRuleInfo() {
      getRuleInfoApi().then(res => {
        if (res.code === 200) {
          this.rule = res.data;
          // 确保分红比例正确计算
          if (this.rule.reserve) {
            this.rule.dividend = 100 - this.rule.reserve;
          }
        }
      });
    },
    confirmDistribution() {
      if (this.distributionSum !== 100) {
        this.$message.warning('请先完善分配规则，确保分红总和为100%');
        this.showEditModal = true;
        return;
      }
      this.showConfirmDialog = true;
    },
    async executeDistribution() {
      this.distributing = true;
      try {
        const res = await executeDistributionApi();
        if (res.code === 200) {
          this.$message.success('分配执行成功');
          this.showConfirmDialog = false;
          // 可以添加刷新数据或其他后续操作
        } else {
          this.$message.error(res.message || '分配执行失败');
        }
      } catch (error) {
        this.$message.error('分配执行失败: ' + (error.message || '未知错误'));
      } finally {
        this.distributing = false;
      }
    }
  },
  created() {
    this.getRuleInfo();
  }
};
</script>

<style scoped>
.distribution-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

/* 规则卡片样式 */
.rule-card {
  border-radius: 8px;
  margin-bottom: 20px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.card-title {
  margin: 0;
  font-size: 18px;
  color: #303133;
  display: flex;
  align-items: center;
}

.card-title i {
  margin-right: 10px;
  font-size: 20px;
  color: #409EFF;
}

.card-actions .el-button {
  margin-left: 10px;
}

/* 规则内容样式 */
.rule-content {
  padding: 20px;
}

/* 描述列表样式 */
.el-descriptions {
  margin-top: 10px;
}

.el-descriptions-item__label {
  font-weight: bold;
  color: #606266;
}

.date-text {
  display: flex;
  align-items: center;
}

.date-text i {
  margin-right: 5px;
  color: #909399;
}

/* 进度条样式 */
.el-progress {
  width: 80%;
  display: inline-block;
  vertical-align: middle;
}

/* 弹窗内容样式 */
.dialog-content {
  padding: 0 20px;
}

.form-item {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.form-label {
  width: 100px;
  text-align: right;
  padding-right: 15px;
  font-size: 14px;
  color: #606266;
}

.hint-text {
  margin-left: 10px;
  font-size: 12px;
  color: #909399;
}

.error-text {
  margin-left: 115px;
  color: #f56c6c;
  font-size: 12px;
}

.distribution-summary {
  margin-top: 20px;
  margin-left: 115px;
}

/* 确认对话框样式 */
.confirm-content {
  padding: 10px;
}

.summary-box {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #dcdfe6;
}

.summary-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.summary-label {
  font-weight: bold;
  color: #606266;
}

.summary-value {
  color: #303133;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .card-actions {
    margin-top: 10px;
    width: 100%;
  }

  .card-actions .el-button {
    margin-left: 0;
    margin-right: 10px;
    margin-bottom: 5px;
  }

  .form-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .form-label {
    width: 100%;
    text-align: left;
    padding-right: 0;
    margin-bottom: 5px;
  }

  .error-text,
  .distribution-summary {
    margin-left: 0;
  }

  .el-progress {
    width: 100%;
  }
}
</style>